package com.itgone.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itgone.bean.PageInfo;
import com.itgone.bean.Product;
import com.itgone.bean.User;
import com.itgone.common.ServerResponse;

import java.util.ArrayList;
import java.util.List;

public class JsonUtil {

    public static final <T> ServerResponse parseResponse(String jsonStr, Class<T> clazz) {
        ServerResponse serverResponse = JSON.parseObject(jsonStr, ServerResponse.class);
        JSONObject parse = (JSONObject) JSONObject.parse(jsonStr);
        Object data = parse.get("data");
        if (data == null) {
            return serverResponse;
        }
        T t = JSON.parseObject(data.toString(), clazz);
        serverResponse.setData(t);
        return serverResponse;
    }

    public static final <T> ServerResponse parseResponsePageList(String jsonStr, Class<T> clazz) {
        ServerResponse serverResponse = JSON.parseObject(jsonStr, ServerResponse.class);
        JSONObject parse = (JSONObject) JSONObject.parse(jsonStr);
        JSONObject data = parse.getJSONObject("data");
        if (data == null) {
            return serverResponse;
        }

        PageInfo pageInfo = JSON.parseObject(data.toJSONString(), PageInfo.class);
        List list = pageInfo.getList();
        ArrayList<T> tList = new ArrayList<>();
        for (Object o : list) {
            T t = JSON.parseObject(o.toString(), clazz);
            tList.add(t);
        }
        pageInfo.setList(tList);
        serverResponse.setData(pageInfo);
        return serverResponse;
    }

    public static void main(String[] args) {
        User user=new User();
        user.setUsername("1212");
        String s = JSON.toJSONString(user);
        System.out.println(s);
    }
}
